package com.whfc.ms.api.emp.controller;

import com.whfc.common.base.BaseController;
import com.whfc.common.result.*;
import com.whfc.common.util.SessionAttr;
import com.whfc.emp.dto.*;
import com.whfc.emp.param.*;
import com.whfc.entity.dto.OssPathDTO;
import com.whfc.fuum.entity.SysUser;
import com.whfc.ms.api.emp.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * 人员管理
 *
 * @author guodong_sun
 * @Description:
 * @date 2019年8月27日
 */
@RestController
@RequestMapping("/ms/api/emp")
public class AppEmpController extends BaseController {

    @Autowired
    private MsAppEmpService msAppEmpService;

    @Autowired
    private MsAppBroadcastService msAppBroadcastService;

    @Autowired
    private MsAppEmpConfigService msAppEmpConfigService;

    @Autowired
    private MsRewardService msRewardService;

    @Autowired
    private MsPayrollService msPayrollService;

    @Autowired
    private MsEmpBlackService msEmpBlackService;

    /**
     * 人员列表
     *
     * @param user
     * @param request
     * @return
     */
    @GetMapping(value = "/list", params = { "pageNum" })
    public Result list(@SessionAttribute(SessionAttr.MS_USER) SysUser user, @Validated AppEmpListParam request) {
        logger.info("人员管理-人员列表，loginer:{},参数AppEmpListParam:{}", user.getUsername(), request.toString());
        PageData<AppEmpDTO> pageData = msAppEmpService.list(request);
        return ResultUtil.success(pageData);
    }

    @GetMapping("/list")
    public Result list(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @RequestParam("deptId") Integer deptId,
            @RequestParam(value = "empName", required = false) String empName) {
        logger.info("人员管理-人员列表(不分页)，loginer:{},deptId:{},empName:{}", user.getUsername(), deptId, empName);
        ListData<AppEmpDTO> listData = msAppEmpService.list(deptId, empName);
        return ResultUtil.success(listData);
    }

    /**
     * 人员列表
     *
     * @param user
     * @param request
     * @return
     */
    @GetMapping(value = "/num")
    public Result num(@SessionAttribute(SessionAttr.MS_USER) SysUser user, @Validated AppEmpListParam request) {
        logger.info("人员管理-人员统计，loginer:{},参数AppEmpListParam:{}", user.getUsername(), request.toString());
        AppEmpNumDTO data = msAppEmpService.num(request);
        return ResultUtil.success(data);
    }

    /**
     * 人员详情
     *
     * @param user
     * @param empId
     * @return
     */
    @GetMapping("/detail")
    public Result detail(@SessionAttribute(SessionAttr.MS_USER) SysUser user, @RequestParam("empId") Integer empId) {
        logger.info("查询人员详情，loginer:{},empId:{}", user.getUsername(), empId);
        AppEmpDTO appEmpDTO = msAppEmpService.detail(empId);
        return ResultUtil.success(appEmpDTO);
    }

    /**
     * 二维码获取人员信息
     *
     * @param empId 人员ID
     * @return
     */
    @GetMapping(value = { "/anon/info/{empId}", "/info/{empId}" })
    public Result info(@PathVariable("empId") Integer empId) {
        logger.info("二维码获取人员信息,empId:{}", empId);
        AppEmpDTO appEmpDTO = msAppEmpService.getEmpInfo(empId);
        return ResultUtil.success(appEmpDTO);
    }

    @GetMapping("/getEmpQr/{empId}")
    public Result getEmpQr(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @PathVariable("empId") Integer empId) throws Exception {
        logger.info("获取人员二维码地址,loginer:{},empId:{}", user.getNickname(), empId);
        OssPathDTO data = msAppEmpService.getEmpQr(empId);
        return ResultUtil.success(data);
    }

    /**
     * 人员管理-添加人员
     *
     * @param user
     * @param request
     * @return
     */
    @RequiresPermissions("emp/list/add")
    @PostMapping("/add")
    public Result add(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @Validated @RequestBody AppEmpAddParam request) {
        logger.info("人员管理-添加人员，loginer:{},", user.getUsername());
        msAppEmpService.add(request);
        return ResultUtil.success();
    }

    /**
     * 人员管理-编辑人员
     *
     * @param user
     * @param request
     * @return
     */
    @RequiresPermissions("emp/list/edit")
    @PostMapping("/edit")
    public Result edit(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @Validated @RequestBody AppEmpEditParam request) {
        logger.info("人员管理-编辑人员，loginer:{},参数AppEmpEditParam:{}", user.getUsername(), request.toString());
        msAppEmpService.edit(request);
        return ResultUtil.success();
    }

    @PostMapping("/anon/syncWorker")
    public Result add(@RequestBody AppEmpEditParam request) {
        logger.info("同步实名制，request:{},", request.toString());
        msAppEmpService.syncWorker(request);
        return ResultUtil.success();
    }

    /**
     * 人员管理-删除人员
     *
     * @param user
     * @param empId
     * @return
     */
    @RequiresPermissions("emp/list/del")
    @PostMapping("/del/{empId}")
    public Result del(@SessionAttribute(SessionAttr.MS_USER) SysUser user, @PathVariable("empId") Integer empId) {
        logger.info("人员管理-删除人员,loginer:{},empId:{}", user.getUsername(), empId);
        msAppEmpService.del(empId);
        return ResultUtil.success();
    }

    @PostMapping("/delList")
    public Result delList(@SessionAttribute(SessionAttr.MS_USER) SysUser user, @RequestBody List<Integer> empIdList) {
        logger.info("人员管理-删除人员,loginer:{},empId:{}", user.getUsername(), empIdList);
        msAppEmpService.delList(empIdList);
        return ResultUtil.success();
    }

    /**
     * 人员管理-上传图片
     *
     * @param user
     * @param base64Str
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("/uploadImg")
    public Result uploadImg(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @RequestParam(value = "base64Str", required = false) String base64Str,
            @RequestParam(value = "file", required = false) MultipartFile file,
            @RequestParam(value = "faceFlag", required = false) Boolean faceFlag) throws IOException {
        logger.info("人员管理-上传图片,loginer:{}", user.getUsername());
        String path = msAppEmpService.uploadImg(base64Str, file, faceFlag);
        return ResultUtil.success(path);
    }

    /**
     * 人员管理-人员入职
     *
     * @param user
     * @param request
     * @return
     */
    @RequiresPermissions("emp/list/enter")
    @PostMapping("/enter")
    public Result enter(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @Validated @RequestBody AppEmpEnterParam request) {
        logger.info("人员管理-人员入职，loginer:{},AppEmpEnterParam:{}", user.getUsername(), request.toString());
        msAppEmpService.enter(request);
        return ResultUtil.success();
    }

    /**
     * 人员管理-人员离职
     *
     * @param user
     * @param request
     * @return
     */
    @RequiresPermissions("emp/list/outer")
    @PostMapping("/outer")
    public Result outer(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @Validated @RequestBody AppEmpOuterParam request) {
        logger.info("人员管理-人员离职，loginer:{},AppEmpOuterParam:{}", user.getUsername(), request.toString());
        msAppEmpService.outer(request);
        return ResultUtil.success();
    }

    /**
     * 人员管理-人员离职(批量)
     *
     * @param user
     * @param request
     * @return
     */
    @RequiresPermissions("emp/list/edit")
    @PostMapping("/outer/batch")
    public Result outerBatch(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @Validated @RequestBody AppEmpOuterBatchParam request) {
        logger.info("人员管理-人员离职，loginer:{},AppEmpOuterParam:{}", user.getUsername(), request.toString());
        msAppEmpService.outer(request);
        return ResultUtil.success();
    }

    /**
     * 人员管理-人员绑定安全帽
     *
     * @param user
     * @param request
     * @return
     */
    @RequiresPermissions("emp/list/bind")
    @PostMapping("/device/bind")
    public Result bind(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @Validated @RequestBody AppEmpDeviceBindParam request) {
        logger.info("人员管理-人员绑定安全帽，loginer:{},AppEmpDeviceBindParam:{}", user.getUsername(), request.toString());
        msAppEmpService.bind(user, request);
        return ResultUtil.success();
    }

    /**
     * 人员管理-人员解除绑定安全帽
     *
     * @param user
     * @param request
     * @return
     */
    @RequiresPermissions("emp/list/unbind")
    @PostMapping("/device/unbind")
    public Result unbind(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @Validated @RequestBody AppEmpDeviceUnbindParam request) {
        logger.info("人员管理-人员解除绑定安全帽，loginer:{},empId:{}", user.getUsername(), request.getEmpId());
        msAppEmpService.unbind(user, request);
        return ResultUtil.success();
    }

    @GetMapping("/device/checkVideoHelmet")
    public Result checkVideoHelmet(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @RequestParam(value = "sn") String sn) {
        logger.info("人员详情-校验是否为视频安全帽，loginer:{},sn:{}", user.getUsername(), sn);
        return ResultUtil.success(msAppEmpService.checkVideoHelmet(user, sn));
    }

    /**
     * @param user
     * @param base64Str
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/cert/uploadCertFile")
    public Result uploadCertFile(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @RequestParam(value = "base64Str", required = false) String base64Str,
            @RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
        logger.info("人员管理-上传证书附件图片,loginer:{}", user.getUsername());
        OssPathDTO path = msAppEmpService.uploadCertFile(base64Str, file);
        return ResultUtil.success(path);
    }

    @PostMapping("/cert/del/{certId}")
    public Result delCert(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @PathVariable("certId") Integer certId) {
        logger.info("删除人员证书，loginer:{},certId:{}", user.getUsername(), certId);
        msAppEmpService.delCert(certId);
        return ResultUtil.success();
    }

    @GetMapping("/cert/list")
    public Result certList(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @RequestParam("empId") Integer empId) {
        logger.info("人员证书列表,loginer:{},empId:{}", user.getUsername(), empId);
        ListData<AppEmpCertDTO> listData = msAppEmpService.certList(empId);
        return ResultUtil.success(listData);
    }

    @PostMapping("/cert/add")
    public Result addCert(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @Validated @RequestBody AppEmpCertAddParam request) {
        logger.info("添加证书,loginer:{},param:{}", user.getUsername(), request.toString());
        msAppEmpService.addCert(request);
        return ResultUtil.success();
    }

    @PostMapping("/cert/edit")
    public Result editCert(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @Validated @RequestBody AppEmpCertEditParam request) {
        logger.info("编辑证书,loginer:{},param:{}", user.getUsername(), request.toString());
        msAppEmpService.editCert(request);
        return ResultUtil.success();
    }

    @GetMapping("/black/list")
    public Result blackList(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @RequestParam("deptId") Integer deptId,
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam("pageSize") Integer pageSize,
            @RequestParam(value = "keyword", required = false) String keyword) {
        logger.info("人员黑名单列表,loginer:{},deptId:{},pageNum:{},pageSize:{},keyword:{}",
                user.getUsername(), deptId, pageNum, pageSize, keyword);
        PageData<AppEmpBlackDTO> pageData = msEmpBlackService.blackList(deptId, pageNum, pageSize, keyword);
        return ResultUtil.success(pageData);
    }

    @GetMapping("/black/getEmpList")
    public Result blackEmpList(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @RequestParam("deptId") Integer deptId) {
        ListData<AppEmpDTO> list = msEmpBlackService.blackEmpList(deptId);
        return ResultUtil.success(list);
    }

    @PostMapping("/black/add")
    public Result blackAdd(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @Validated @RequestBody AppEmpBlackAddParam request) {
        logger.info("添加人员黑名单,loginer:{},param:{}", user.getUsername(), request.toString());
        msEmpBlackService.blackAdd(user, request);
        return ResultUtil.success();
    }

    @PostMapping("/black/del/{id}")
    public Result blackDel(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @PathVariable("id") Integer id) {
        logger.info("删除黑名单,loginer:{},id:{}", user.getUsername(), id);
        msEmpBlackService.blackDel(id);
        return ResultUtil.success();
    }

    @PostMapping("/black/delList")
    public Result blackDel(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @RequestBody List<Integer> ids) {
        logger.info("批量删除黑名单,loginer:{},ids:{}", user.getUsername(), ids.toString());
        msEmpBlackService.blackDelList(ids);
        return ResultUtil.success();
    }

    @GetMapping("/getSetting")
    public Result getSetting(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @RequestParam("deptId") Integer deptId) {
        logger.info("查询人员实名制设置,loginer:{},deptId:{}", user.getUsername(), deptId);
        AppEmpSettingDTO empSettingDTO = msAppEmpConfigService.getSetting(deptId);
        return ResultUtil.success(empSettingDTO);
    }

    @RequiresPermissions("emp/rule")
    @PostMapping("/setting/add")
    public Result settingAdd(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @Validated @RequestBody AppEmpSettingAddParam request) {
        logger.info("添加人员实名制设置,loginer:{},param:{}", user.getUsername(), request.toString());
        msAppEmpConfigService.settingAdd(request);
        return ResultUtil.success();
    }

    @PostMapping("/broadcast")
    public Result broadcast(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @Validated @RequestBody AppEmpBroadcastParam request) {
        logger.info("发送人员广播,loginer:{},param:{}", user.getUsername(), request.toString());
        request.setSendUserId(user.getId());
        request.setSendUserName(user.getUsername());
        msAppBroadcastService.broadcast(request);
        return ResultUtil.success();
    }

    @PostMapping("/attendQr/download/{deptId}")
    public Result downloadAttendQr(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @PathVariable("deptId") Integer deptId) {
        logger.info("下载考勤二维码,loginer:{},deptId:{}", user.getUsername(), deptId);
        OssPathDTO data = msAppEmpConfigService.downloadAttendQr(deptId);
        return ResultUtil.success(data);
    }

    @PostMapping("/empQr/download/{deptId}")
    public Result downloadEmpQr(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @PathVariable("deptId") Integer deptId) {
        logger.info("下载考勤二维码,loginer:{},deptId:{}", user.getUsername(), deptId);
        OssPathDTO data = msAppEmpConfigService.downloadEmpQr(deptId);
        return ResultUtil.success(data);
    }

    @GetMapping(value = { "/attendQr/anon/check", "/attendQr/check" })
    public Result checkAttendQr(@RequestParam("deptId") Integer deptId) {
        logger.info("验证考勤二维码是否启用,deptId:{}", deptId);
        boolean data = msAppEmpConfigService.checkAttendQr(deptId);
        return ResultUtil.success(data);
    }

    @GetMapping("/empQr/check")
    public Result checkEmpQr(@RequestParam("deptId") Integer deptId) {
        logger.info("验证考勤二维码是否启用,deptId:{}", deptId);
        boolean data = msAppEmpConfigService.checkEmpQr(deptId);
        return ResultUtil.success(data);
    }

    @GetMapping("/getRewardList")
    public Result getRewardList(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @RequestParam("empId") Integer empId) {
        logger.info("根据人员id查找奖惩记录列表,loginer:{},empId:{}", user.getUsername(), empId);
        ListData<AppEmpRewardDTO> listData = msRewardService.getRewardList(empId);
        return ResultUtil.success(listData);
    }

    @GetMapping("/getPayrollList")
    public Result getPayrollList(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @RequestParam("empId") Integer empId) {
        logger.info("根据人员id查找工资发放列表,loginer:{},empId:{}", user.getUsername(), empId);
        ListData<AppPayrollEmpDTO> listData = msPayrollService.getPayrollList(empId);
        return ResultUtil.success(listData);
    }

    @PostMapping("/export")
    public Result export(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @Validated @RequestBody AppEmpListExportParam param) throws Exception {
        logger.info("导出人员列表:loginer:{},param:{}", user.getUsername(), param.toString());
        OssPathDTO data = msAppEmpService.export(param);
        return ResultUtil.success(data);
    }

    @PostMapping("/anon/upload/sgin")
    public Result uploadSignImg(@RequestParam("signImg") String signImg,
            @RequestParam("id") Integer id,
            @RequestParam("type") String type,
            @RequestParam(value = "empId", required = false) Integer empId) {
        logger.info("人员-上传签名图片,trainEmpId:{}, type:{}, empId:{}", id, type, empId);
        msAppEmpService.uploadSignImg(signImg, id, type, empId);
        return ResultUtil.success();
    }

    @PostMapping("/upload/img")
    public Result uploadImg(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @RequestParam("file") MultipartFile file,
            @RequestParam("module") String module) {
        logger.info("人员-上传图片, loginer:{}, module:{}", user.getUsername(), module);
        OssPathDTO ossPathDTO = msAppEmpService.uploadImg(file, module);
        return ResultUtil.success(ossPathDTO);
    }

    @PostMapping("/import")
    public Result empImport(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
            @RequestParam("deptId") Integer deptId,
            @RequestParam("file") MultipartFile file) {
        logger.info("人员-导入人员, loginer:{}, module:{}", user.getUsername(), deptId);
        msAppEmpService.importEmp(deptId, file);
        return ResultUtil.success();
    }

    /**
     * 通过deptId查询所在项目所有班主长信息
     *
     * @param deptId 部门ID
     * @return 班组长信息列表
     */
    @GetMapping(value = "/leaderList")
    public R<List<AppEmpDTO>> leaderList(@RequestParam Integer deptId) {
        logger.info("查询部门下班组长列表, deptId: {}", deptId);
        // 调用现有服务获取所有人员列表
        List<AppEmpDTO> empDTOList = msAppEmpService.getLeaderList(deptId, null);
        return R.success(empDTOList);
    }
}